#![allow(non_snake_case)]

use super::{
    bottons::ButtonProp,
    edit_row_state::{EditColumn, EditRowState},
};
use crate::components::crud::{parse_condition, ControlLayout};
use leptos::prelude::*;
use leptos_icons::*;
use serde_json::Value;

use shq_common::prelude::Layout;
use thaw_utils::class_list;
#[component]
pub fn DataEditInner(
    #[prop(into)] field_props: Signal<Vec<EditColumn>>,
    edit_row_data: ReadSignal<EditRowState>,
    #[prop(optional, into)] button_props: Vec<ButtonProp>,
) -> impl IntoView {
    let button_props = StoredValue::new(button_props);
    let buttons_view = move || {
        let props = button_props.get_value();
        props
            .into_iter()
            .map(|prop| {
                view! {
                    <button class="btn btn-sm" on:click=move|_|{
                        let vals:Vec<(String,Value)>=edit_row_data.with(|s| {
                            s.iter().map(|v| {
                                (v.name.to_string(), v.value.get())
                            }).collect::<Vec<_>>()
                        });
                        (prop.on_click)(vals);
                    }>
                        <Icon icon=prop.icon/>
                        {prop.text.clone()}
                    </button>
                }
            })
            .collect::<Vec<_>>()
    };
    let layout_view = move || {
        field_props.with(|cols| {
            let mut row_indexs: Vec<Vec<usize>> = Vec::new();
            let mut row_index = 0_usize;
            let mut gsum = 0_u8;
            for (i, col) in cols.iter().enumerate() {
                if gsum == 0 || gsum + col.edit_props.grid > 12 {
                    row_indexs.push(vec![i]);
                    if gsum > 0 {
                        row_index += 1
                    };
                    gsum = col.edit_props.grid;
                } else {
                    gsum = gsum + col.edit_props.grid;
                    row_indexs[row_index].push(i);
                }
            }
            let rlen=row_indexs.len();
            row_indexs.iter().map(|row| {
                view! {
                    <div class=class_list!["grid gap-2 justify-between grid-flow-col"]>
                        {
                            row.iter().map(|i|{
                                let c = &cols[*i];
                                let val = edit_row_data.with(|v|v.get_value(c.name.as_str()).map(|v|v.clone())).unwrap();
                                let err_msg = edit_row_data.with(|v|v.get_err_msg(c.name.as_str()).map(|v|v.clone())).unwrap();
                                let res=if let Some(dis)=c.edit_props.disabled.as_ref() {
                                    parse_condition(dis, edit_row_data)
                                }else{
                                    Ok(false)
                                };
                                match res {
                                    Ok(disabled) => {
                                        let col_span=c.edit_props.grid;
                                        let col=StoredValue::new(c.clone());
                                        let inner_max_width=col_span as u32*18;
                                        either_of::Either::Left(view! {
                                            <div class=move||format!("col-span-{}",col_span) >
                                                <ControlLayout col disabled val layout=Layout::Horizontal err_msg=err_msg.read_only() inner_max_width/>
                                            </div>
                                        })
                                    },
                                    Err(err) => either_of::Either::Right(view! { <p class="text-red-500">{err.to_string()}</p> }),
                                }
                            }).collect_view()
                        }
                        {
                            if rlen==1 {
                                Some(buttons_view)
                            } else {
                                None
                            }
                        }
                    </div>
                }
            }).collect_view()
        })
    };
    view! {
        {
            view!{
                <div class="bg-base-100">
                    <div class="flex flex-col gap-4">
                        {layout_view}
                    </div>
                </div>
            }.into_any()
        }
    }
}
